package hos.load

import androidx.lifecycle.LifecycleOwner

/**
 * <p>Title: LoadableDataImpl </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-08-15 10:15
 * @version : 1.0
 */
abstract class LoadableDataImpl<DATA>(lifecycleOwner: LifecycleOwner) :
    LoadableImpl(lifecycleOwner),
    LoadableData<DATA> {

    private val mLoadDataList by lazy { mutableListOf<DATA?.() -> Unit>() }

    override fun onDestroy() {
        super.onDestroy()
        mLoadDataList.clear()
    }

    override fun loading() {
        var data: DATA? = null
        try {
            data = loadData()
        } finally {
            mLoadDataList.forEach {
                it.invoke(data)
            }
        }
    }

    abstract fun loadData(): DATA

    override fun addDoneDataLoadingListener(runnable: DATA?.() -> Unit) {
        if (!mLoadDataList.contains(runnable)) {
            mLoadDataList.add(runnable)
        }
    }

    override fun removeDoneDataLoadingListener(runnable: DATA?.() -> Unit): Boolean {
        if (mLoadDataList.contains(runnable)) {
            return mLoadDataList.remove(runnable)
        }
        return true
    }
}